package com.xindaoapp.happypet.ui;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.view.photoview.PhotoView;

/**
 * 图片
 * 
 * @author xindaoapp
 * 
 */
public class MyImgsFragment extends BaseFragment {

    private PhotoView photoView;
    private ProgressBar pb_loading;
    private String url;
    private final static String IMG_KEY = "img_key";
    DisplayImageOptions options; // DisplayImageOptions是用于设置图片显示的类


    public static MyImgsFragment newInstance(String imgUrl) {
        MyImgsFragment fragment = new MyImgsFragment();
        Bundle bundle = new Bundle();
        bundle.putString(IMG_KEY, imgUrl);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_img, container, false);
        return mView;
    }

    @Override
    protected void initViews() {
        // TODO Auto-generated method stub
        super.initViews();

        options = new DisplayImageOptions.Builder().showStubImage(R.drawable.about_logo) //
                // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.about_logo) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.about_logo) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                .displayer(new RoundedBitmapDisplayer(0)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象


        if (!ImageLoader.getInstance().isInited()) {
            ImageLoaderConfiguration config =
                    new ImageLoaderConfiguration.Builder(getActivity()).build();
            ImageLoader.getInstance().init(config);
        }
        url = getArguments().getString(IMG_KEY);
        photoView = (PhotoView) mView.findViewById(R.id.iv_photo);
        pb_loading = (ProgressBar) mView.findViewById(R.id.pb_loading);

        // ImageLoader.getInstance().displayImage(url, photoView, options,
        // new AnimateFirstDisplayListener());
        pb_loading.setVisibility(View.VISIBLE);
        ImageLoader.getInstance().displayImage(url, photoView, new AnimateFirstDisplayListener());
        // ImageLoader.getInstance().getDiscCache().get(url).getPath();

    }

    @Override
    protected void loadDatas() {
        super.loadDatas();

    }

    /**
     * 图片加载第一次显示监听器
     * 
     * @author Administrator
     * 
     */
    private class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
        ProgressDialog dialog;

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                // 是否第一次显示
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    // 图片淡入效果
                    pb_loading.setVisibility(View.GONE);
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }

        @Override
        public void onLoadingStarted(String imageUri, View view) {
            // TODO Auto-generated method stub
            super.onLoadingStarted(imageUri, view);
            pb_loading.setVisibility(View.VISIBLE);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            // TODO Auto-generated method stub
            super.onLoadingFailed(imageUri, view, failReason);
            pb_loading.setVisibility(View.GONE);
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            // TODO Auto-generated method stub
            super.onLoadingCancelled(imageUri, view);
            pb_loading.setVisibility(View.GONE);
        }
    }

    /**
     * 保存图片到SD卡上
     * 
     * @param bm
     * @param fileName
     * 
     */
    public void saveFileToSD(Drawable dw, String url) {
        // SD卡上图片储存地址
        final String path = Environment.getExternalStorageDirectory().getPath() + "/weibaquan";
        final String path2 =
                Environment.getExternalStorageDirectory().getPath() + "/weibaquan/image";
        try {
            BitmapDrawable bd = (BitmapDrawable) dw;
            Bitmap bm = bd.getBitmap();

            // 获得文件名字
            final String fileNa =
                    url.substring(url.lastIndexOf("/") + 1, url.length()).toLowerCase();
            File file = new File(path + "/image/" + fileNa);
            // 创建图片缓存文件夹
            boolean sdCardExist =
                    Environment.getExternalStorageState().equals(
                            android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
            if (sdCardExist) {
                File weibaquan = new File(path);
                File ad = new File(path + "/image");
                // 如果文件夹不存在
                if (!weibaquan.exists()) {
                    // 按照指定的路径创建文件夹
                    weibaquan.mkdir();
                    // 如果文件夹不存在
                } else if (!ad.exists()) {
                    // 按照指定的路径创建文件夹
                    ad.mkdir();
                }
                // 检查图片是否存在
                if (!file.exists()) {
                    file.createNewFile();
                }
            }

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        Toast.makeText(mContext, "图片保存到" + path2, Toast.LENGTH_SHORT);
    }
}
